package com.apes.fn.fico.expense.platformFee.process;

import com.apes.fn.fico.expense.platformFee.CommonFeeProcess;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.income.model.MoneyIncome;
import com.apes.scm.income.model.MoneyIncomeItem;
import com.apes.scm.income.repository.MoneyIncomeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 资金收入单生成平台费用细项单据
 */
@Service
public class MoneyIncomeFeeProcess extends CommonFeeProcess {

    @Autowired
    MoneyIncomeRepository moneyIncomeRepository;

    @Override
    public void process(SimpleRequest request) {
        String id = request.get("id");
        MoneyIncome moneyIncome = moneyIncomeRepository.findOne(id);
        createExpense(MapUtil.mapper("order", moneyIncome));
    }

    /**
     * 货币资金平台服务费
     *
     * @param map {"order": MoneyIncome}
     */
    @Override
    public Map<String, Object> getExpenseModel(Map map) {
        MoneyIncome moneyIncome = (MoneyIncome) map.get("order");
        List<MoneyIncomeItem> moneyIncomeItemList = moneyIncome.getMoneyIncomeItems().stream()
                .filter(moneyIncomeItem -> !"05".equals(moneyIncomeItem.getPaymentMethodType().getId()))
                .collect(Collectors.toList());
        if (moneyIncomeItemList.isEmpty()) return null;
        double paymentAmount = moneyIncomeItemList.stream().mapToDouble(MoneyIncomeItem::getIncomeAmount).sum();
        double expenseAmount = moneyIncomeItemList.stream().mapToDouble(MoneyIncomeItem::getPlatformManagementFee).sum();
        return MapUtil.mapper("order", moneyIncome.getId(), "orderType", "MoneyIncome",
                "source", moneyIncome.getId(), "sourceBusinessType", "MoneyIncome","date",moneyIncome.getApproveDate(),
                "summary", "", "incomeTypeId", "A09", "expenseDetailsTypeId", "002051",
                "paymentAmount", paymentAmount, "expenseAmount", expenseAmount,
                "deptId", moneyIncome.getDept().getId(), "companyId", moneyIncome.getCompany().getId());
    }

    @Override
    public boolean support(String type) {
        return "MoneyIncome".equals(type);
    }

}
